﻿using System;
using System.Drawing;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using PockeTwit.OtherServices;
using PockeTwit.OtherServices.TextShrinkers;

namespace FingerUI
{
    public partial class FullScreenTweet : UserControl
    {
        const string HTMLTagPattern = "<.*?>";

        public PockeTwit.Library.status Status;
        public Yedda.Twitter Conn;
        private bool _visible;
        public new bool Visible
        {
            get
            {
                return _visible;
            }
            set
            {
                _visible = value;
                base.Visible = value;
                if (_visible)
                {
                    PockeTwit.ThrottledArtGrabber.NewArtWasDownloaded += ThrottledArtGrabberNewArtWasDownloaded;
                }
                else
                {
                    PockeTwit.ThrottledArtGrabber.NewArtWasDownloaded -= ThrottledArtGrabberNewArtWasDownloaded;
                    if (avatarBox.Image != null)
                    {
                        avatarBox.Image.Dispose();
                    }
                }
            }
        }
        public FullScreenTweet()
        {
            InitializeComponent();
            if (PockeTwit.DetectDevice.DeviceType == PockeTwit.DeviceType.Standard)
            {
                lnkDismiss.Visible = false;
            }
            _fontSize = lblText.Font.Size;
            PockeTwit.Themes.FormColors.SetColors(this);
            PockeTwit.Localization.XmlBasedResourceManager.LocalizeForm(this);
            avatarBox.Width = ClientSettings.SmallArtSize;
            avatarBox.Height = ClientSettings.SmallArtSize;
            thumbnailPicBox.Width = ClientSettings.SmallArtSize;
            thumbnailPicBox.Height = ClientSettings.SmallArtSize;
            attachPicBox.Width = ClientSettings.SmallArtSize;
            attachPicBox.Height = ClientSettings.SmallArtSize;
            lblRText.BackColor = ClientSettings.RTBackColor;
            pRT.BackColor = ClientSettings.RTBackColor;
        }

        public void ResetRendering()
        {
            PockeTwit.Themes.FormColors.SetColors(this);
            PockeTwit.Localization.XmlBasedResourceManager.LocalizeForm(this);
        }

        private delegate void DelUpdateArt(string argument);
        void ThrottledArtGrabberNewArtWasDownloaded(string argument)
        {
            
            if (Status != null)
            {
                if (argument == Status.user.profile_image_url)
                {
                    if (InvokeRequired)
                    {
                        var d = new DelUpdateArt(ThrottledArtGrabberNewArtWasDownloaded);
                        Invoke(d, argument);
                    }
                    else
                    {
                        try
                        {
                            avatarBox.Image = PockeTwit.ThrottledArtGrabber.GetArt(Status.user.profile_image_url);
                        }
                        catch(ObjectDisposedException){}
                    }
                }
            }
        }

        private float _fontSize;
        public float FontSize
        {
            get { return _fontSize; }
            set
            {
                if (value > 5)
                {
                    _fontSize = value;
                    using (var textFont = new Font(FontFamily.GenericSansSerif, value, FontStyle.Regular))
                    {
                        lblText.Font = textFont;
                    }
                }
            }
        }

        private int contentHeight = 0;

        public void Render()
        {
            if (Status != null)
            {
                Cursor.Current = Cursors.WaitCursor;

                pFullScreenContent.Top = 0;
                attachPicBox.Visible = false;
                thumbnailPicBox.Visible = false;
                lblRText.Visible = false;
                pRT.Visible = false;
                PockeTwit.Library.status stat = Status;

                //if (Status.retweeted_status != null)
                //{
                //    //why won't this work? does retweeted_status need to 
                //    //be saved in the db?
                //    stat = Status.retweeted_status;
                //}

                //if it's a new retweet, make an API call to get orginal tweet
                //so we can show all 140 chars of the tweet
                //if (Status.TypeofMessage == PockeTwit.Library.StatusTypes.Retweet)
                //{
                //    foreach (Yedda.Twitter.Account a in ClientSettings.AccountsList)
                //    {
                //        if (a.Equals(Status.Account))
                //        {
                //            Yedda.Twitter.Account NewAccount = new Yedda.Twitter.Account
                //            {
                //                ServerURL = a.ServerURL,
                //                UserName = a.UserName,
                //                Password = a.Password,
                //                Enabled = a.Enabled,
                //                OAuth_token = a.OAuth_token,
                //                OAuth_token_secret = a.OAuth_token_secret
                //            };
                //            Conn = Yedda.Servers.CreateConnection(NewAccount);

                //            //Get the tweet again from Twitter
                //            stat = PockeTwit.Library.status.DeserializeSingle(Conn.ShowSingleStatus(stat.id), Conn.AccountInfo);

                //            //Set the tweet to the original tweet
                //            stat = stat.retweeted_status;
                //            break;
                //        }
                //    }
                //}

                avatarBox.Width = ClientSettings.SmallArtSize;
                avatarBox.Height = ClientSettings.SmallArtSize;

                avatarBox.Image = PockeTwit.ThrottledArtGrabber.GetArt(stat.user.profile_image_url);
                //lblUserName.Text = stat.user.screen_name;
                lblUserName.Text = stat.user.name;
                lblTime.Text = stat.TimeStamp;
                if (string.IsNullOrEmpty(stat.source))
                {
                    lblSource.Text = "";
                }
                else
                {

                    lblSource.Text = PockeTwit.Localization.XmlBasedResourceManager.GetString("from ") + StripHTML(System.Web.HttpUtility.HtmlDecode(stat.source));
                }
                string fullText;
                if (ShortText.IsShortTextURL(stat.text))
                {
                    string[] splitup = stat.text.Split(new[] { ' ' });
                    fullText = ShortText.GetFullText(splitup[splitup.Length - 1]);
                }
                else
                {
                    fullText = stat.text;
                }
                if (ClientSettings.AutoTranslate)
                {
                    fullText = GoogleTranslate.GetTranslation(fullText);
                }
                lblText.Text = System.Web.HttpUtility.HtmlDecode(fullText).Replace("&", "&&");

                {
                    Bitmap bmp = new Bitmap(50, 50);
                    Graphics g = Graphics.FromImage(bmp);
                    int lineOffset = 1;
                    string textToDisplay = lblText.Text;

                    SizeF size = g.MeasureString(textToDisplay, lblText.Font);
                    while (size.Width > lblText.Width)
                    {
                        {
                            int totalChars = textToDisplay.Length;
                            int estimatedChars = Math.Min((((lblText.Width) * totalChars) / (int)size.Width) + 2, textToDisplay.Length - 1);
                            bool spaceBreak = true;
                            string line = textToDisplay;
                            int endOfLine = estimatedChars;
                            while (size.Width > lblText.Width)
                            {
                                endOfLine = textToDisplay.LastIndexOf('\n', estimatedChars);
                                if (endOfLine < 0) { endOfLine = estimatedChars; spaceBreak = false; }
                                line = textToDisplay.Substring(0, endOfLine);
                                size = g.MeasureString(line, lblText.Font);
                                estimatedChars = endOfLine - 1;
                            }
                            textToDisplay = spaceBreak ? textToDisplay.Substring(endOfLine + 1) : textToDisplay.Substring(endOfLine);
                            size = g.MeasureString(textToDisplay, lblText.Font);
                            lineOffset++;
                        }
                    }
                    lblText.Height = (int)(lineOffset * size.Height) + 1;
                }
                contentHeight = lblText.Bottom + 5;

                if (!string.IsNullOrEmpty(Status.thumbnail_pic) || !string.IsNullOrEmpty(Status.small_pic))
                {
                    thumbnailPicBox.Location = new System.Drawing.Point(3, lblText.Bottom + 3);
                    string picPath = "";

                    if(!string.IsNullOrEmpty(Status.thumbnail_pic))
                        picPath = PockeTwit.ThrottledArtGrabber.GetImagePathFromURL(Status.thumbnail_pic);
                    else if(!string.IsNullOrEmpty(Status.small_pic))
                        picPath = PockeTwit.ThrottledArtGrabber.GetImagePathFromURL(Status.small_pic);
                    Image img = new System.Drawing.Bitmap(picPath);
                    //if (img.Height > thumbnailPicBox.Height)
                    //{
                    //    thumbnailPicBox.Width = img.Width * thumbnailPicBox.Height / img.Height;
                    //}
                    //else
                    //{
                    //    thumbnailPicBox.Width = img.Width;
                    //    thumbnailPicBox.Height = img.Height;
                    //}
                    //thumbnailPicBox.Width = img.Width * ClientSettings.SmallArtSize / img.Height;
                    thumbnailPicBox.Width = img.Width * thumbnailPicBox.Height / img.Height;
                    //thumbnailPicBox.Height = ClientSettings.SmallArtSize;

                    thumbnailPicBox.Image = img;
                    thumbnailPicBox.Visible = true;

                    contentHeight = thumbnailPicBox.Bottom + 5;
                }

                if (!string.IsNullOrEmpty(Status.RText))
                {
                    if (thumbnailPicBox.Visible == true)
                        this.pRT.Location = new System.Drawing.Point(4, thumbnailPicBox.Bottom + 3);
                        //this.lblRText.Location = new System.Drawing.Point(4, attachPicBox.Bottom + 3);
                    else
                        this.pRT.Location = new System.Drawing.Point(4, lblText.Bottom + 3);
                        //this.lblRText.Location = new System.Drawing.Point(4, lblText.Bottom + 3);

                    lblRText.Text = System.Web.HttpUtility.HtmlDecode("@" + Status.RTUserName + ":" + Status.RText).Replace("&", "&&");

                    {
                        Bitmap bmp = new Bitmap(50, 50);
                        Graphics g = Graphics.FromImage(bmp);
                        int lineOffset = 1;
                        string textToDisplay = lblRText.Text;

                        SizeF size = g.MeasureString(textToDisplay, lblRText.Font);
                        while (size.Width > lblRText.Width)
                        {
                            {
                                int totalChars = textToDisplay.Length;
                                int estimatedChars = Math.Min((((lblRText.Width) * totalChars) / (int)size.Width) + 2, textToDisplay.Length - 1);
                                bool spaceBreak = true;
                                string line = textToDisplay;
                                int endOfLine = estimatedChars;
                                while (size.Width > lblRText.Width)
                                {
                                    endOfLine = textToDisplay.LastIndexOf('\n', estimatedChars);
                                    if (endOfLine < 0) { endOfLine = estimatedChars; spaceBreak = false; }
                                    line = textToDisplay.Substring(0, endOfLine);
                                    size = g.MeasureString(line, lblRText.Font);
                                    estimatedChars = endOfLine - 1;
                                }
                                textToDisplay = spaceBreak ? textToDisplay.Substring(endOfLine + 1) : textToDisplay.Substring(endOfLine);
                                size = g.MeasureString(textToDisplay, lblRText.Font);
                                lineOffset++;
                            }
                        }
                        lblRText.Height = (int)(lineOffset * size.Height) + 1;
                    }
                    lblRText.Visible = true;
                    pRT.Height = lblRText.Height + 8;

                    if (!string.IsNullOrEmpty(Status.RThumbnail_pic))
                    {
                        this.attachPicBox.Location = new System.Drawing.Point(3, lblRText.Bottom + 3);
                        if (Status.Account.Server == Yedda.Twitter.TwitterServer.sohu && 0 == Status.RThumbnail_pic.CompareTo("true"))
                        {
                            PockeTwit.Library.status RTStatus = null;
                            Yedda.Twitter Conn;

                            Conn = Yedda.Servers.CreateConnection(Status.Account);
                            try
                            {
                                RTStatus = PockeTwit.Library.status.DeserializeSingle(Conn.ShowSingleStatus(Status.RTID), Status.Account);
                                if (RTStatus != null)
                                {
                                    if (!string.IsNullOrEmpty(RTStatus.small_pic))
                                        Status.RThumbnail_pic = RTStatus.small_pic;
                                    if (!string.IsNullOrEmpty(RTStatus.middle_pic))
                                        Status.RTmiddle_pic = RTStatus.middle_pic;
                                    if (!string.IsNullOrEmpty(RTStatus.original_pic))
                                        Status.RToriginal_pic = RTStatus.original_pic;
                                }
                            }
                            catch
                            {
                            }
                        }
                        string picPath = PockeTwit.ThrottledArtGrabber.GetImagePathFromURL(Status.RThumbnail_pic);
                        Image img = new System.Drawing.Bitmap(picPath);
                        //if (img.Height > attachPicBox.Height)
                        //{
                        //    attachPicBox.Width = img.Width * attachPicBox.Height / img.Height;
                        //}
                        //else
                        //{
                        //    attachPicBox.Width = img.Width;
                        //    attachPicBox.Height = img.Height;
                        //}
                        //attachPicBox.Width = img.Width * ClientSettings.SmallArtSize / img.Height;
                        attachPicBox.Width = img.Width * attachPicBox.Height / img.Height;
                        //attachPicBox.Height = ClientSettings.SmallArtSize;

                        attachPicBox.Image = img;
                        attachPicBox.Visible = true;

                        pRT.Height += attachPicBox.Height + 7;
                    }
                    pRT.Visible = true;

                    contentHeight = pRT.Bottom + 5;
                }

                //pFullScreenContent.Height = contentHeight;

                Cursor.Current = Cursors.Default;
                lnkDismiss.BringToFront();
            }
        }

        private void lnkDismiss_Click(object sender, EventArgs e)
        {
            Visible = false;
        }
        static string StripHTML(string inputString)
        {
            if (string.IsNullOrEmpty(inputString)) { return null; }
            return Regex.Replace
              (inputString, HTMLTagPattern, string.Empty);
        }

        private int mouseDownOn = 0;

        private void pFullScreenContent_MouseMove(object sender, MouseEventArgs e)
        {
            int mouseMoved = e.Y - mouseDownOn;
            pFullScreenContent.Top = pFullScreenContent.Top + mouseMoved;
        }

        private void pFullScreenContent_MouseDown(object sender, MouseEventArgs e)
        {
            mouseDownOn = e.Y;
        }

        private void pFullScreenContent_MouseUp(object sender, MouseEventArgs e)
        {
            mouseDownOn = 0;
            timeranimate.Enabled = true;
        }

        private void timeranimate_Tick(object sender, EventArgs e)
        {
            int offSet = pFullScreenContent.Top;
            int step = offSet / 4;
            if (step < 5 && step > 0)
            {
                step = 5;
            }
            if (step > -5 && step < 0)
            {
                step = -5;
            }
            if (step == 0)
            {
                timeranimate.Enabled = false;
                return;
            }
            if (offSet > 0)
            {
                pFullScreenContent.Top = pFullScreenContent.Top - step;
                if (pFullScreenContent.Top < 0)
                {
                    pFullScreenContent.Top = 0;
                    timeranimate.Enabled = false;
                }
            }
            //else
            //{
            //    pFullScreenContent.Top = pFullScreenContent.Top - step;
            //    if (pFullScreenContent.Top > 0)
            //    {
            //        pFullScreenContent.Top = 0;
            //        timeranimate.Enabled = false;
            //    }
            //}
            else if(offSet < 0 && offSet < pFullScreenView.Height - lnkDismiss.Height - contentHeight)
            {
                pFullScreenContent.Top = pFullScreenContent.Top - step;
                if (pFullScreenContent.Top > pFullScreenView.Height - lnkDismiss.Height - contentHeight)
                {
                    pFullScreenContent.Top = pFullScreenView.Height - lnkDismiss.Height - contentHeight;
                    timeranimate.Enabled = false;
                }
            }
        }
    }
}
